//
//  PlayViewController.m
//  Atlantis
//
//  Created by 何恩营 on 14-12-17.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.

// 播放页面

#import "PlayViewController.h"
#import "PlayDetailsViewController.h"
#import "UIImageView+WebCache.h"
#import "NetHandler.h"
#import "AVPlayer+player.h"
#import "BaseObject.h"
#import "JingRoundView.h"
#import <ShareSDK/ShareSDK.h>
#import "DataBaseHandler.h"
#import "Reachability.h"
#import "MBProgressHUD.h"

#define REUSE @"reuse"

@interface PlayViewController ()

// 专辑详情
@property(nonatomic, retain) Music *musicDetail;
// 播放器
@property(nonatomic, retain) AVPlayer *avplay;
// 声音图片视图
@property(nonatomic, retain) UIImageView *imageView;
// 播主名
@property(nonatomic, retain) UILabel *labelID;
// 声音滑动条
//@property(nonatomic, retain) UISlider *volumeSlider;
// 播主信息字典
@property(nonatomic, retain) NSMutableDictionary *nickDic;
// 圆盘音乐
@property(nonatomic, retain) JingRoundView *jinground;
// 进度滑动条
@property(nonatomic, retain) UISlider *timeSlider;
// 进度时间框
@property(nonatomic, retain) UILabel *timeLabel;
// 播放按钮
@property(nonatomic, retain) UIButton *playButton;
// 下一曲按钮
@property(nonatomic, retain) UIButton *downButton;
// 上一曲按钮
@property(nonatomic, retain) UIButton *upButton;
// 收藏按钮图片
@property(nonatomic, retain) UIImage *collectImage;
// 旋转风火轮
@property(nonatomic, retain) MBProgressHUD *hud;

@property(nonatomic, retain) NSMutableData *mutableData;
@property(nonatomic, retain) NSURLResponse *response;


@end

@implementation PlayViewController{
    UIAlertView *alert;
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.musicArr = [NSArray array];
    }
    return self;
}

// 内存管理
- (void)dealloc
{
    // 播放按钮
    [_playButton release];
    // 下一曲按钮
    [_downButton release];
    // 上一曲按钮
    [_upButton release];
    // 声音对象
    [_music release];
    // 专辑详情
    [_musicDetail release];
    // 播放器
    [_avplay release];
    // 声音图片视图
    [_imageView release];
    // 播主名
    [_labelID release];
    // 声音滑动条
    //[_volumeSlider release];
    // 播主信息字典
    [_nickDic release];
    // 圆盘音乐
    [_jinground release];
    // 进度时间框
    [_timeLabel release];
    // 进度滑动条
    [_timeSlider release];
    // 播放数组
    [_musicArr release];
    // 收藏按钮图片
    [_collectImage release];
    [super dealloc];
}


// 播放器单例
+(PlayViewController *)sharePlayVC
{
    static PlayViewController *play;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        play = [[PlayViewController alloc] init];
    });
    return play;
}

// 实现方法
- (void)play
{
    // 处理数据
    [self handleData];
}

//视图即将出现
- (void)viewWillAppear:(BOOL)animated
{
    // 继承父类
    [super viewWillAppear:animated];
    
    // 始终空出导航栏的高度
    self.navigationController.navigationBar.translucent = NO;
    
    // 判断网络字符串是否为空
    if ([self GetCurrntNet]) {
        // 不为空, 则处理网络数据
        // 调用数据处理方法
        [self handleData];
        // 文本显示
        self.hud.labelText = @"loading...";
        
    }else {
        // 否则检查网络
        self.hud.labelText = @"亲,请检查您的网络";
    }
    
    // 刷新数据
    [self.view reloadInputViews];
    
}


// 处理数据
- (void)handleData
{
    // 判断专辑视图是否为空
    if (self.musicArr != nil) {
        // 不为空, 则赋值
        self.music = [self.musicArr objectAtIndex:self.currentMusic];
    }
    
    // 创建网络请求
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", self.music.trackId];
    //NSLog(@"%@", self.music.trackId);
    
    // 建立连接
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        
        // JSON解析
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // 初始化
        self.musicDetail = [[Music alloc] initWithDictionary:result];
        // 内存管理
        [_musicDetail release];
        
       
        // 专辑详情播放视图赋值图片
        [self.imageView setImageWithURL:[NSURL URLWithString:self.musicDetail.coverLarge]];
        
        // navigationbar标题
        self.navigationItem.title = self.musicDetail.title;
        // 如果不为空, 播放64
        [self.avplay playWithURL:[NSURL URLWithString:self.musicDetail.playUrl64] isPlay:1];

        // 赋值 - 利用tag获取
        self.jinground = (JingRoundView *)[self.tabBarController.tabBar viewWithTag:100];
        
        // 赋值
        self.timeLabel.text = [NSString stringWithFormat:@"00:00/%@", [self timeTransfer:self.musicDetail.duration]];
   
        // 建立连接
        [NetHandler getDataWithURL:self.musicDetail.coverSmall completion:^(NSData *data) {
            
            // 赋值
            self.jinground.roundImage = [UIImage imageWithData:data];
            
            // 播放
            self.jinground.isPlay = YES;
        }];
        
        
        // 初始化播主信息字典
        self.nickDic = [NSMutableDictionary dictionary];
        // 获取数据
        self.nickDic = [result objectForKey:@"userInfo"];
        // 赋值
        self.labelID.text = [@"by " stringByAppendingString:[self.nickDic objectForKey:@"nickname"]];
    }];
    
    // 风火轮视图移除
    [self.hud removeFromSuperview];
}




// 实现方法
- (NSString *)timeTransfer:(NSInteger)duration
{
    // 判断播放时间
    if (duration / 60 >= 10) {
        return [NSString stringWithFormat:@"%ld:%ld", duration / 60, duration % 60];
    } else {
        if (duration % 60 < 10) {
            return [NSString stringWithFormat:@"0%ld:0%ld", duration / 60, duration % 60];
        }
        return [NSString stringWithFormat:@"0%ld:%ld", duration / 60, duration % 60];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
   

    // 右上角收藏
    // 图片赋值
    self.collectImage = [UIImage imageNamed:@"shoucang.png"];
    // 图片原型显示
    self.collectImage = [self.collectImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    // 收藏按钮触发事件
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:self.collectImage style:UIBarButtonItemStyleDone target:self action:@selector(collectionAction:)] autorelease];
    
    
    
    // 设置背景颜色
    self.view.backgroundColor = [UIColor whiteColor];
    // 创建专辑详情播放视图并设置大小
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width)];
    // 将专辑详情播放视图加载到视图上
    [self.view addSubview:self.imageView];
    // 图片透明度
    self.imageView.alpha = 0.8;
    // 图片视图启用用户交互
    self.imageView.userInteractionEnabled = YES;
    // 内存管理
    [_imageView release];

    
    // 播放单例
    self.avplay = [AVPlayer shareAVPlayer];


    
    // 播放进度条
    self.timeSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, self.imageView.bounds.size.height - 20, self.imageView.bounds.size.width - 60, 20)];
    // 默认值
    self.timeSlider.value = 0.0f;
    // 触发事件
    [self.timeSlider addTarget:self action:@selector(changeTimerValue:) forControlEvents:UIControlEventValueChanged];
    // 视图加载
    [self.imageView addSubview:_timeSlider];
    // 图片
    UIImage *image = [UIImage imageNamed:@"quare1.png"];
    // 设置图片
    [self.timeSlider setThumbImage:image forState:UIControlStateNormal];
    // 内存管理
    [_timeSlider release];
    
    // 触发事件
    [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(changeTimer) userInfo:nil repeats:YES];

    
    
    // 播放进度时间显示
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.imageView.bounds.size.width - 60, self.imageView.bounds.size.height - 20, 60, 15)];
    // 设置背景颜色
    self.timeLabel.backgroundColor = [UIColor whiteColor];
    // 视图加载
    [self.imageView addSubview:self.timeLabel];
    // 设置字体大小
    self.timeLabel.font = [UIFont systemFontOfSize:10];
    // 内存管理
    [_timeLabel release];

    
    // 上一曲, 下一曲, 播放按钮的视图
    UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 190, self.view.bounds.size.width, 50)];
    
    // 播放按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeSystem];
    // 设置播放按钮大小
    self.playButton.frame = CGRectMake(buttonView.frame.size.width / 2 - 25, 0, 50, 50);
    // 设置播放按钮图片
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"pause-big.png"] forState:UIControlStateNormal];
    // 触发事件
    [self.playButton addTarget:self action:@selector(pauseButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // 播放按钮视图加载
    [buttonView addSubview:self.playButton];
    
    
    // 下一曲
    self.downButton = [UIButton buttonWithType:UIButtonTypeSystem];
    // 设置大小
    self.downButton.frame = CGRectMake(buttonView.frame.size.width / 2 + 70, 10, 30, 30);
    // 设置下一曲图片
    [self.downButton setBackgroundImage:[UIImage imageNamed:@"xiayiqu.png"] forState:UIControlStateNormal];
    // 触发事件
    [self.downButton addTarget:self action:@selector(downButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // 下一曲按钮视图加载
    [buttonView addSubview:self.downButton];
    
    
    // 上一曲
    self.upButton = [UIButton buttonWithType:UIButtonTypeSystem];
    // 设置大小
    self.upButton.frame = CGRectMake(buttonView.frame.size.width / 2 - 100, 10, 30, 30);
    // 设置上一曲图片
    [self.upButton setBackgroundImage:[UIImage imageNamed:@"shangyiqu.png"] forState:UIControlStateNormal];
    // 触发事件
    [self.upButton addTarget:self action:@selector(upButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // 上一曲按钮视图加载
    [buttonView addSubview:self.upButton];
    
    
    // 按钮视图加载
    [self.view addSubview:buttonView];
    // 内存管理
    [buttonView release];
    
    
    // 创建播放音频的ID视图并设置大小
    self.labelID = [[UILabel alloc]initWithFrame:CGRectMake(10, self.view.bounds.size.width + 30, self.view.bounds.size.width / 2, self.view.bounds.size.width / 8)];
    // 设置背景颜色
    //self.labelID.backgroundColor = [UIColor redColor];
    // 字体居中
    self.labelID.textAlignment = NSTextAlignmentCenter;
    // 将ID视图加载到视图上
    [self.view addSubview:self.labelID];
    // 内存管理
    [_labelID release];
    
    
    
    // 创建详情按钮视图
    UIButton *detailsButton = [UIButton buttonWithType:UIButtonTypeSystem];
    // 设置大小
    detailsButton.frame = CGRectMake(self.view.bounds.size.width / 2 + 25, self.view.bounds.size.width + 30, self.view.bounds.size.width / 6 - 10, self.view.bounds.size.width / 8);
    // 设置详情按钮显示文字
    [detailsButton setTitle:@"详情" forState:UIControlStateNormal];
    // 设置详情按钮的背景颜色
    [detailsButton setBackgroundColor:[UIColor whiteColor]];
    // 详情按钮的实现方法
    [detailsButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    // 将详情按钮加载到视图上
    [self.view addSubview:detailsButton];
  
    
    // 分享图片视图
    UIImageView *shareImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width / 6 * 4 + 10, self.view.bounds.size.width + 30, self.view.bounds.size.width / 8 - 5, self.view.bounds.size.width / 8)];
    // 分享图片视图赋值
    shareImageView.image = [UIImage imageNamed:@"share_128.png"];
    // 视图加载
    [self.view addSubview:shareImageView];
    // 内存管理
    [shareImageView release];
    
    
    // 分享按钮
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
    // 设置大小
    shareButton.frame = CGRectMake(self.view.bounds.size.width / 4 * 3, self.view.bounds.size.width + 30, self.view.bounds.size.width / 6, self.view.bounds.size.width / 8);
    // 按钮文字
    [shareButton setTitle:@"分享" forState:UIControlStateNormal];
    // 按钮触发事件
    [shareButton addTarget:self action:@selector(shareButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // 视图加载
    [self.view addSubview:shareButton];
    
    
    // 导航栏左侧返回按钮
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"return.png"] style:UIBarButtonItemStyleDone target:self action:@selector(leftCollectionAction:)] autorelease];
    
    
    
    // 风火轮
    self.hud = [[MBProgressHUD alloc]initWithView:self.view];
    // 风火轮模式
    [self.hud setMode:MBProgressHUDModeIndeterminate];
    // 显示
    [self.hud show:YES];
    // 加载到视图上
    [self.view addSubview:_hud];
    
    
    
}

// 判断有无网络连接
-(NSString*) GetCurrntNet
{
    NSString* result;
    Reachability *r = [Reachability reachabilityWithHostname:@"www.apple.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:     // 没有网络连接
            result=nil;
            break;
        case ReachableViaWWAN: // 使用3G网络
            result=@"3G";
            break;
        case ReachableViaWiFi: // 使用WiFi网络
            result=@"WiFi";
            break;
    }
    return result;
}



// 导航栏左侧返回按钮触发事件
- (void)leftCollectionAction:(UINavigationBar *)bar
{
    //NSLog(@"返回前一页");
    // 推出前一页
    [self.navigationController popViewControllerAnimated:YES];
}



// 分享按钮触发事件
- (void)shareButtonClicked:(UIButton *)sender
{
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
    
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:[self.music.title stringByAppendingString:self.music.playUrl64] defaultContent:@"测试一下" image:[ShareSDK imageWithPath:imagePath] title:@"ShareSDK" url:@"http://www.mob.com" description:@"这是一条测试信息" mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container shareList:nil content:publishContent statusBarTips:YES authOptions:nil shareOptions:nil result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        
        NSLog(@"STATE = %d",state);
        
        if (state == SSResponseStateSuccess)
        {
            NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
        }
        else if (state == SSResponseStateFail)
        {
            NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
        }
    }];

}




#warning 收藏实现??
//  收藏按钮实现方法
- (void)collectionAction:(UIBarButtonItem *)collection
{
    // 创建字典
    self.detailsDic = [NSMutableDictionary dictionary];
    // 赋值
    [self.detailsDic setValue:self.music.title forKey:@"title"];
    [self.detailsDic setValue:self.music.trackId forKey:@"trackId"];
    //NSLog(@"-----%@", self.music.trackId);
    // 建立数据库
    DataBaseHandler *newsCollect = [DataBaseHandler shareInstance];
    // 打开数据库
    [newsCollect openDB];
    // 创建表
    [newsCollect createTable];
    // 添加数据
    BOOL result = [newsCollect insertMusic:self.detailsDic];
    //NSLog(@"%@.........", self.detailsDic);
    if (result) {
        // 警告窗
        alert = [[UIAlertView alloc] initWithTitle:@"" message:@"已加入收藏列表" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }else {
        // 警告窗
        alert = [[UIAlertView alloc] initWithTitle:@"" message:@"该内容已经收藏过了" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
 }

// 进度条
- (void)changeTimer
{
    // 播放器当前事件 / 播放器延续时间
    float value = CMTimeGetSeconds(self.avplay.currentItem.currentTime) / CMTimeGetSeconds(self.avplay.currentItem.duration);
    // 设置值
    self.timeSlider.value = value;
    // 文本显示
    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@", [self timeTransfer:(NSInteger)CMTimeGetSeconds(self.avplay.currentItem.currentTime)], [self timeTransfer:self.musicDetail.duration]];
}

// 更改时间触发事件
- (void)changeTimerValue:(id)sender
{
    // 设置滑动条
    UISlider *slider = (UISlider *)sender;
    // 音量赋值
    float value = slider.value;
    // 时间赋值
    int32_t timer = self.avplay.currentItem.asset.duration.timescale;
    // 时间赋值
    Float64 timeValue = CMTimeGetSeconds(self.avplay.currentItem.duration) * value;
    // 播放器寻求时间
    [self.avplay seekToTime:CMTimeMakeWithSeconds(timeValue, timer) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
    // 判断播放是否结束
    if (CMTimeGetSeconds(self.avplay.currentTime) == CMTimeGetSeconds(self.avplay.currentItem.duration)) {
        [self pauseButtonClicked:nil];
    } else {
        [self playButtonClicked:nil];
    }
}

// 上一曲按钮实现方法
- (void)upButtonClicked:(UIButton *)button
{
    // 判断当前音乐是否为第一首歌
    if (self.currentMusic == 0) {
        // 如果是, 提示已经为第一首
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经为第一首" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        // 警告窗显示
        [alertView show];
        // 内存管理
        [alertView release];
    } else {
        // 如果不是, currentMusic - 1, 申请上一首歌的数据
        self.currentMusic -= 1;
        // 调用处理数据
        [self handleData];
    }
}

// 下一曲按钮实现方法
- (void)downButtonClicked:(UIButton *)button
{
    // 判断当前音乐是否为最后一曲
    if (self.currentMusic == self.musicArr.count - 1) {
        // 如果是最后一首, 提示已经是最后一首歌
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经是最后一首了" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        // 警告窗显示
        [alertView show];
        // 内存管理
        [alertView release];
    } else {
        // 如果不是, currentMusic + 1, 申请下一首歌的数据
        self.currentMusic += 1;
        // 调用处理数据
        [self handleData];
    }
}


// 播放按钮实现方法
- (void)playButtonClicked:(UIButton *)playButton
{
   // NSLog(@"%ld", self.flag);
    
    // 把播放图标背景换成暂停图标
    [playButton setBackgroundImage:[UIImage imageNamed:@"pause-big.png"] forState:UIControlStateNormal];
    // 实现暂停按钮的方法
    [playButton addTarget:self action:@selector(pauseButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // 播放器播放
    [self.avplay play];
    // 圆盘播放器播放
    self.jinground.isPlay = YES;
}




// 暂停图标按钮实现的方法
- (void)pauseButtonClicked:(UIButton *)pauseButton
{
    //NSLog(@"暂停");
    // 将暂停图标换成播放图标
    [pauseButton setBackgroundImage:[UIImage imageNamed:@"start-big.png"] forState:UIControlStateNormal];
    // 实现播放按钮的方法
    [pauseButton addTarget:self action:@selector(playButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // 圆盘播放器暂停
    self.jinground.isPlay = NO;
    // 播放暂停
    [self.avplay pause];
}

// 详情按钮实现方法
- (void)buttonAction:(UIButton *)button
{
    // 创建详情页面
    PlayDetailsViewController *playDetailsVC = [[PlayDetailsViewController alloc]init];
    // 赋值
    playDetailsVC.music = self.musicDetail;
    // 推出页面
    [self.navigationController pushViewController:playDetailsVC animated:YES];
    // tableBar显示
    self.tabBarController.tabBar.hidden = NO;
    // 内存管理
    [playDetailsVC release];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
